package com.study.transaction.order.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: chenhs
 * @date: Created in 10:46 2019/12/17
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderDatabaseService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 保存订单记录
     *
     * @param orderInfo 订单内容
     * @throws Exception
     */
    public void saveOrder(JSONObject orderInfo) throws Exception {
        String sql = "insert into table_order (order_id, user_id, order_content, create_time) values (?, ?, ?, now())";

        //添加订单记录
        jdbcTemplate.update(sql, orderInfo.get("orderId"), orderInfo.get("userId"), orderInfo.get("orderContent"));

        //保存所有要发送到MQ的消息，防止没有发送就挂了
        saveLocalMessage(orderInfo);
    }


    /**
     * 消息发送计划表，防止漏发
     * table_distributed_message 默认发送状态0-未发送，1-已发送
     * 不建议在订单添加消息发送状态 - 解耦！
     * @param orderInfo
     * @throws Exception
     */
    public void saveLocalMessage(JSONObject orderInfo) throws Exception {
        String sql = "insert into table_distributed_message (unique_id, msg_content) values (?, ?)";
        jdbcTemplate.update(sql, orderInfo.getString("orderId"), orderInfo.toJSONString());
    }



    public List<JSONObject> listUnDispatch() {
        List<JSONObject> rs = new ArrayList<>();
        String sql = "select msg_content from table_distributed_message where msg_status = 0";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

        for (Map map: list) {
            JSONObject object = JSONObject.parseObject(map.get("msg_content").toString());
            rs.add(object);
        }

        return rs;
    }
}
